using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UniversalAdmin.Application.Dto;
using UniversalAdmin.Application.Commands;
using UniversalAdmin.Domain.Entities.App;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Shared.Enums;

namespace UniversalAdmin.Application.Services;

public class AppRoleMenuServices : IAppRoleMenuServices
{
    private readonly IRepository<AppRole> _roleRepository;
    private readonly IRepository<AppMenu> _menuRepository;
    public AppRoleMenuServices(IRepository<AppRole> roleRepository, IRepository<AppMenu> menuRepository)
    {
        _roleRepository = roleRepository;
        _menuRepository = menuRepository;
    }

    public async Task<ApiResult> AssignMenusAsync(AssignRoleMenusDto dto)
    {
        var role = await _roleRepository.GetByIdAsync(dto.RoleId);
        if (role == null) return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "角色不存在");
        var menus = _menuRepository.Table.Where(m => dto.MenuIds.Contains(m.Id)).ToList();
        if (menus.Count != dto.MenuIds.Count)
            return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "部分菜单不存在");
        // 覆盖式分配
        role.Menus.Clear();
        foreach (var menu in menus)
            role.Menus.Add(menu);
        await _roleRepository.UpdateAsync(role);
        return ApiResult.Success((int)ApiStatusCode.SUCCESS, "分配菜单成功");
    }

    public async Task<ApiResult<IEnumerable<string>>> GetRoleMenusAsync(Guid roleId)
    {
        var role = await _roleRepository.GetByIdAsync(roleId);
        if (role == null) return ApiResult<IEnumerable<string>>.Failed(404, "角色不存在");
        var menus = role.Menus.Select(m => m.MenuName);
        return ApiResult<IEnumerable<string>>.Success(menus);
    }

    public async Task<ApiResult> RemoveRoleMenuAsync(Guid roleId, Guid menuId)
    {
        var role = await _roleRepository.GetByIdAsync(roleId);
        if (role == null) return ApiResult.Failed(404, "角色不存在");
        var menu = role.Menus.FirstOrDefault(m => m.Id == menuId);
        if (menu == null) return ApiResult.Failed(404, "菜单不存在");
        role.Menus.Remove(menu);
        await _roleRepository.UpdateAsync(role);
        return ApiResult.Success("移除成功");
    }
} 